import { createWebHashHistory, createRouter } from "vue-router";
import NotFound from '@/components/NotFound.vue'
import Home from "@/pages/index.vue";
import Login from "@/pages/login.vue";
import Admin from "../layouts/admin.vue";
import Shopping from "../pages/goods/list.vue";
import Category from '@/pages/goods/category.vue';
import Comment from "../pages/comment/list.vue";
import Coupon from "../pages/coupon/list.vue";
import Image from "../pages/image/list.vue";
import Notice from "../pages/notice/list.vue";
import Order from "../pages/order/list.vue";
import Setting from "../pages/setting/base.vue";
import User from "../pages/user/list.vue";

// 默认路由，所有用户共享
const routes = [
  {
    path: "/",
    component: Admin,
    name: 'admin',
    meta: {
      title: '后台首页'
    },
  },
  {
    path: "/login",
    component: Login,
    name: 'Login',
    meta: {
      title: '登录页面'
    }
  },
  { path: "/:pathMatch(.*)*", name: "NotFound", component: NotFound },
];
// 动态路由，用于匹配菜单动态添加路由 
const asyncRoutes = [
  {
    path: "/",
    component: Home,
    name: '/',
    meta: {
      title: '后台首页'
    },
  },
  {
    path: '/goods/list',
    component: Shopping,
    name: '/goods/list',
    meta: {
      title: '商品管理'
    }
  }, {
    path: '/category/list',
    component: Category,
    name: '/category/list',
    meta: {
      title: '分类管理'
    }
  }, {
    path: '/user/list',
    component: User,
    name: '/user/list',
    meta: {
      title: '用户管理'
    }
  }, {
    path: '/order/list',
    component: Order,
    name: '/order/list',
    meta: {
      title: '订单管理'
    }
  }, {
    path: '/comment/list',
    component: Comment,
    name: '/comment/list',
    meta: {
      title: '评价管理'
    }
  }, {
    path: '/image/list',
    component: Image,
    name: '/image/list',
    meta: {
      title: '图库管理'
    }
  }, {
    path: '/notice/list',
    component: Notice,
    name: '/notice/list',
    meta: {
      title: '公告管理'
    }
  }, {
    path: '/setting/base',
    component: Setting,
    name: '/setting/base',
    meta: {
      title: '配置管理'
    }
  }
  , {
    path: '/coupon/list',
    component: Coupon,
    name: '/coupon/list',
    meta: {
      title: '优惠券管理'
    }
  }
]
export const router = createRouter({
  // 注：createWebHashHistory是带#的，但是不利于seo（参考公司的企业应用平台就是带#），如果是createWebHistory则是不带#的，但是有利于seo（参考b站的官网就是不带#的，有利于seo）。
  history: createWebHashHistory(),
  routes,
});
// // 就是把asyncRoutes中的路由放进routes中去
export function addRoutes(menus) {

  let defaultChange = false;
  /** 定义一个函数进行递归调用 */
  const findAndAddRoute = (arr) => {
    arr.forEach(r => {
      let item = asyncRoutes.find(e => e.path === r.frontpath);

      if (item && !router.hasRoute(item.name)) {
        router.addRoute('admin', item);
        defaultChange = true;
      }
      if (r.child && r.child.length > 0) {
        findAndAddRoute(r.child);
      }
    });
  }
  findAndAddRoute(menus);
  // console.log('查看现有路由', router.getRoutes());
  return defaultChange;
}
